<?php


namespace App\Repositories;


use App\Models\Receiving as Model;
use App\Traits\Logs;
use Exception;
use LTools\Repositories\RepositoryAbstract;
use LTools\Traits\CodeTrait;

class Receiving extends RepositoryAbstract
{
    use CodeTrait, Logs;

    /**
     * Receiving constructor.
     * @param Model $model
     * @author luffyzhao@vip.126.com
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $attributes
     * @return bool|\Illuminate\Database\Eloquent\Model
     * @author luffyzhao@vip.126.com
     */
    public function create(array $attributes = [])
    {
        /** @var \App\Models\Customer $customer */
        $customer = app('customer');
        $attributes['code'] = $this->unique(6, 'R' . $customer->getAttribute('code'));
        $attributes['price'] = collect($attributes['products'])->sum(function ($item) {
            return bcmul($item['quantity'], $item['price'], 3);
        });
        $attributes['product_count'] = collect($attributes['products'])->sum('quantity');

        /** @var Model $model */
        $model = parent::create($attributes);
        // 产品
        $model->products()->createMany(
            $this->productsTransform($attributes['products'])
        );
        // 文件
        $model->files()->createMany(
            collect($attributes['files'])->map(function ($item) {
                return collect($item)->only(['type', 'url']);
            })->toArray()
        );
        // 日志
        $this->recordLogs($model, '添加入库单');
        return $model;
    }

    /**
     * @param $id
     * @param array $values
     * @return bool|\Illuminate\Database\Eloquent\Model
     * @throws \Throwable
     * @author luffyzhao@vip.126.com
     */
    public function update($id, array $values)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if($model->canModify()){
            $values['price'] = collect($values['products'])->sum(function ($item) {
                return bcmul($item['quantity'], $item['price'], 3);
            });
            $values['product_count'] = collect($values['products'])->sum('quantity');


            $model->fill($values)->saveOrFail();;
            // 先删
            $model->products()->delete();
            $model->files()->delete();

            // 产品
            $model->products()->createMany(
                $this->productsTransform($values['products'])
            );
            // 文件
            $model->files()->createMany(
                collect($values['files'])->map(function ($item) {
                    return collect($item)->only(['type', 'url']);
                })->toArray()
            );
            // 日志
            $this->recordLogs($model, '修改入库单');
            return $model;
        }
        throw new Exception("不是草稿状态不能修改！");
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     * @author luffyzhao@vip.126.com
     */
    public function edit($id)
    {
        return $this->model->with(['files', 'products.product'])->find($id);
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     * @author luffyzhao@vip.126.com
     */
    public function show($id)
    {
        return $this->model->with(['files', 'products.product', 'logs.user'])->find($id);
    }

    /**
     * @param $id
     * @return bool|mixed|null
     * @throws Exception
     * @author luffyzhao@vip.126.com
     */
    public function delete($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if($model->canDelete()){
            return $model->delete();
        }
        throw new Exception('不是草稿状态不能删除');
    }

    /**
     * @param $id
     * @return bool|mixed|null
     * @throws Exception
     * @throws \Throwable
     * @author luffyzhao@vip.126.com
     */
    public function confirm($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if($model->isDraft()){
            $model->setAttribute('status', 1);
            $model->saveOrFail();
            return $model;
        }
        throw new Exception('不是草稿状态不能确认');
    }

    /**
     * @param array $values
     * @return array
     * @author luffyzhao@vip.126.com
     */
    protected function productsTransform(array $values)
    {
        return collect($values)->map(function ($item) {
            /** @var \App\Models\Customer $customer */
            $customer = app('customer');
            /** @var \App\Models\Product $product */
            $item['product_id'] = \App\Models\Product::query()
                ->where('customer_id', '=', $customer->getKey())
                ->where('sku', '=', $item['sku'])->value('id');
            return collect($item)->only(['product_id', 'quantity', 'price', 'lot']);
        })->toArray();
    }
}
